<template>
    <el-card shadow="hover" class="rounded-lg">
        <template #header>
            <div class="flex items-center justify-between">
                <span>订单统计</span>
                <div>
                    <el-check-tag v-for="(item, index) in options" :key="index" :checked="current == item.value"
                        class="mx-1" @click="handleSelectTag(item.value)">{{ item.text }}</el-check-tag>
                </div>
            </div>
        </template>
        <div id="IndexChart" ref="el" style="height: 330px; width: 100%;">

        </div>
    </el-card>
</template>
<script setup>
import { ref, onMounted, onBeforeMount } from 'vue'
import * as echarts from 'echarts'
import { getStatistics3 } from '../api/index'
import { useResizeObserver } from '@vueuse/core'

const options = [{
    text: "近一个月",
    value: "month"
}, {
    text: "近一周",
    value: "week"
}, {
    text: "近24小时",
    value: "hour"
}]

const current = ref("week")

const handleSelectTag = (type) => {
    if (current.value != type) {
        current.value = type
        refreshChart()
    }
}

const option = {
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: {
        type: 'value'
    },
    grid: {
        left: '5%',    // 距离左边界的距离
        right: '5%',   // 距离右边界的距离
        top: '5%',     // 距离顶部边界的距离
        bottom: '10%'   // 距离底部边界的距离
    },
    series: [
        {
            data: [],
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
            }
        }
    ]
}

const refreshChart = async () => {
    const res = await getStatistics3(current.value)
    // console.log('refreshChart.res=',res)
    if (res.data && res.data.x && res.data.y) {
        option.xAxis.data = res.data.x
        option.series[0].data = res.data.y
    }
    option && myIndexChart.myChart.setOption(option)
}

const myIndexChart = {
    chartDom: null,
    myChart: null
}
// 在页面加载完毕后，初始化EChart控件，并请求后台数据并渲染EChart
onMounted(() => {
    myIndexChart.chartDom = document.getElementById('IndexChart')
    if(myIndexChart.chartDom) {
        myIndexChart.myChart = echarts.init(myIndexChart.chartDom)
        refreshChart()
    }
})

// 在页面销毁前，使用EChart的方法对控件进行dispose，否则页面在重新onMounted的时候就会出现问题
onBeforeMount(()=>{
    if(myIndexChart.myChart) echarts.dispose()
})

const el = ref(null)

// 监听el组件，即图表组件的尺寸发生变化
useResizeObserver(el, (entries) => {
    if(myIndexChart.myChart) myIndexChart.myChart.resize()
})
</script>